/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.iecg.controller.app;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iecg.api.entity.IecgCheckImg;
import com.iecg.service.IecgCheckImgService;
import com.iecg.service.IecgUserService;
import com.pig4cloud.common.minio.service.MinioTemplate;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 检验图片
 *
 * @author zjc
 * @date 2019-10-14 17:55:12
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("app/img" )
@Api(value = "app_iecgcheckimg", tags = "App检验图片管理")
public class AppCheckImgController {

	private final IecgUserService iecgUserService;

    private final IecgCheckImgService iecgCheckImgService;

	private final MinioTemplate minioTemplate;

	/**
	 * 上传文件
	 * 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
	 *
	 * @param file 资源
	 * @return R(bucketName, filename)
	 */
	@PostMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file) {
		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("bucketName", CommonConstants.BUCKET_NAME);
		resultMap.put("fileName", fileName);

		try {
			minioTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());
		} catch (Exception e) {
			log.error("上传失败", e);
			return R.failed(e.getLocalizedMessage());
		}
		return R.ok(resultMap);
	}


	/**
	 * 新增附件图片
	 * @param iecgCheckImg 新增附件图片
	 * @return R
	 */
	@ApiOperation(value = "新增附件图片", notes = "新增附件图片")
	@SysLog("新增附件图片")
	@PostMapping
	public R save(@RequestBody IecgCheckImg iecgCheckImg) {
		iecgCheckImg.setUserId(iecgUserService.getSecurityUser().getId());
		return R.ok(iecgCheckImgService.save(iecgCheckImg));
	}

	/**
	 * 获取文件
	 *
	 * @param fileName 文件空间/名称
	 * @param response
	 * @return
	 */
	@GetMapping("/file/{fileName}")
	public void file(@PathVariable String fileName, HttpServletResponse response) {
		try (InputStream inputStream = minioTemplate.getObject(CommonConstants.BUCKET_NAME, fileName)) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			IoUtil.copy(inputStream, response.getOutputStream());
		} catch (Exception e) {
			log.error("文件读取异常", e);
		}
	}

	/**
	 * 根据userId查询
	 * @param userId
	 * @return
	 */
	@ApiOperation(value = "通过userId查询", notes = "通过userId查询")
	@GetMapping("/user/{userId}" )
	public R getByUserId(@PathVariable("userId") Long userId) {
		return R.ok(iecgCheckImgService.list(Wrappers.<IecgCheckImg>query()
				.lambda().eq(IecgCheckImg::getUserId, userId)).stream()
				.sorted(Comparator.comparing(IecgCheckImg::getCreateTime).reversed()).collect(Collectors.toList()));
	}

    /**
     * 通过id删除检验图片
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除检验图片", notes = "通过id删除检验图片")
    @SysLog("通过id删除检验图片" )
    @DeleteMapping("/{id}" )
    public R removeById(@PathVariable Long id) {
        return R.ok(iecgCheckImgService.removeById(id));
    }


	/**
	 *
	 * @param img
	 * @return
	 */
	@ApiOperation(value = "通过名称删除检验图片", notes = "通过名称删除检验图片")
	@SysLog("通过名称删除检验图片" )
	@DeleteMapping("/name/{img}" )
	public R removeByImg(@PathVariable String img) {
		return R.ok(iecgCheckImgService.remove(Wrappers.<IecgCheckImg>query()
				.lambda().eq(IecgCheckImg::getCheckImg, img)));
	}


	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param iecgCheckImg 检验图片
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page" )
	public R getIecgCheckImgPage(Page page, IecgCheckImg iecgCheckImg) {
		iecgCheckImg.setUserId(iecgUserService.getSecurityUser().getId());
		return R.ok(iecgCheckImgService.selectPage(page, Wrappers.query(iecgCheckImg)));
	}
}
